package net.sf.rose.business.action.define;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.rose.business.action.Download;
import net.sf.rose.business.bean.base.DownloadFileBean;
import net.sf.rose.business.bean.database.FieldMetaBean;
import net.sf.rose.business.bean.database.LinkMetaBean;
import net.sf.rose.business.bean.database.TableMetaBean;
import net.sf.rose.business.service.DataBaseService;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.util.ListProperty;
import net.sf.rose.web.OnlineUserListener;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 功能：
 * 
 * @author fengjian
 * @since 2014/01/29
 */
@Controller
@RequestMapping("/define/database")
public class DataBaseController {

	private static String LIST_PAGE = "define/database/list";
	private static String VIEW_PAGE = "define/database/edit";
	private static String SQL_PAGE = "define/database/sql";

	/**
	 * 普通查询
	 */
	@RequestMapping("/list.html")
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		return mav;
	}

	/**
	 * 普通查询
	 */
	@RequestMapping("/search.html")
	public ModelAndView search(HttpServletRequest request, String tableName, String tableText) {
		Map<String, TableMetaBean> map = this.getTables(tableName, tableText);
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		mav.addObject("list", map);
		mav.addObject("tableName", tableName);
		mav.addObject("tableText", tableText);
		return mav;
	}

	private Map<String, TableMetaBean> getTables(String tableName, String tableText) {
		Map<String, TableMetaBean> map = null;
		Map<String, TableMetaBean> bean = DataBaseService.getService().getAll();
		if (tableName == null || tableName.equals("")) {
			map = bean;
		} else {
			map = new HashMap<String, TableMetaBean>();
			for (String key : bean.keySet()) {
				TableMetaBean a = bean.get(key);
				if (a.getName().indexOf(tableName) != -1) {
					map.put(key, a);
				}
			}
		}
		if (tableText != null && !tableText.trim().equals("")) {
			Map<String, TableMetaBean> m = new HashMap<String, TableMetaBean>();
			for (String key : map.keySet()) {
				TableMetaBean a = map.get(key);
				if (a.getText().indexOf(tableText) != -1) {
					m.put(key, a);
				}
			}
			map = m;
		}
		return map;
	}

	/**
	 * 
	 */
	@RequestMapping("/add.html")
	public ModelAndView add(HttpServletRequest request) {
		TableMetaBean bean = new TableMetaBean();
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", bean);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/get.html")
	public ModelAndView get(HttpServletRequest request, String name) {
		TableMetaBean bean = DataBaseService.getService().getTable(name);
		ModelAndView mav = new ModelAndView(VIEW_PAGE);
		mav.addObject("bean", bean);
		return mav;
	}

	/**
	 * 
	 */
	@RequestMapping("/delete.html")
	public ModelAndView delete(HttpServletResponse response, String name) throws Exception {
		DataBaseService.getService().remove(name);
		response.reset();
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw = response.getWriter();
		pw.write("{\"msg\":\"删除成功！\"}");
		pw.flush();
		pw.close();
		return null;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/save.html")
	public ModelAndView save(HttpServletRequest request, TableMetaBean bean) {
		bean.setFields(this.getFieldBeanList(request));
		DataBaseService.getService().addTableMetaBean(bean);
		ModelAndView mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	private List<FieldMetaBean> getFieldBeanList(HttpServletRequest request) {
		List<FieldMetaBean> list = new ArrayList<FieldMetaBean>();
		int i = 0;
		do {
			// 字段名称
			String name = request.getParameter("items.name[" + i + "]");
			if (name == null || name.equals("")) {
				break;
			}
			FieldMetaBean param = new FieldMetaBean();
			param.setName(name);
			// 字段说明
			String text = request.getParameter("items.text[" + i + "]");
			if (text != null && !text.equals("")) {
				param.setText(text);
			}
			// 数据类型
			String type = request.getParameter("items.type[" + i + "]");
			if (type != null && !type.equals("")) {
				param.setType(type);
			}
			// 长度
			String size = request.getParameter("items.size[" + i + "]");
			if (size != null && !size.equals("")) {
				param.setSize(size);
			}
			// 主键
			String pk = request.getParameter("items.pk[" + i + "]");
			if (pk != null && !pk.equals("")) {
				if (pk.equals("1")) {
					param.setPk(true);
				}
			}
			// 可否为NULL
			String canNull = request.getParameter("items.canNull[" + i + "]");
			if (canNull != null && !canNull.equals("")) {
				if (canNull.equals("1")) {
					param.setCanNull(true);
				}
			}
			// 默认值
			String defaultValue = request.getParameter("items.defaultValue[" + i + "]");
			if (defaultValue != null && !defaultValue.equals("")) {
				param.setDefaultValue(defaultValue);
			}
			// 连接
			String linkField = request.getParameter("items.linkField[" + i + "].name");
			if (linkField != null && !linkField.equals("")) {
				linkField = request.getParameter("items.linkField[" + i + "].id");
				if (linkField != null && !linkField.equals("")) {
					String[] arr = StringUtils.split(linkField, '.');
					LinkMetaBean link = new LinkMetaBean();
					link.setTable(arr[0]);
					link.setField(arr[1]);
					// 连接类型
					String linkType = request.getParameter("items.linkType[" + i + "]");
					link.setType(Integer.parseInt(linkType));
					param.setLink(link);
				}
			}
			list.add(param);
			i++;
		} while (i > 0);
		return list;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/saveAll.html")
	public ModelAndView saveAll(HttpServletRequest request) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		DataBaseService.save(user);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/createSql.html")
	public ModelAndView createSql(HttpServletRequest request) {
		DataBaseService.getService().createDatabaseUpdateSql();
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/getSql.html")
	public ModelAndView getSql(HttpServletRequest request) {
		List<String> list = DataBaseService.getService().getDatabaseUpdateSql();
		ModelAndView mav = new ModelAndView(SQL_PAGE);
		mav.addObject("bean", list);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/execute.html")
	public ModelAndView execute(HttpServletRequest request) {
		UserBean user = OnlineUserListener.getOnlineUser(request);
		DataBaseService.getService().executeDatabaseUpdateSql(user);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/datasource.html")
	public ModelAndView datasource(HttpServletRequest request) {
		String properties = request.getParameter("properties").trim();
		if (properties != null && properties.length() > 0) {
			ListProperty pro = new ListProperty();
			for (String str : StringUtils.split(properties, "\r\n")) {
				if (str.indexOf(0) == '#') {
					pro.addComment(str);
				} else {
					String[] arr = StringUtils.split(str, '=');
					if (arr.length == 2) {
						pro.set(arr[0], arr[1]);
					}
				}
			}
			// DataBaseFactory.saveProperties(pro);
		}
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "操作成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/input.html")
	public ModelAndView input(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(Download.TEMP_FILES);
		if (obj == null) {
			throw new SystemException("Session中找不到上传的文件。", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		Map<String, DownloadFileBean> map = (Map<String, DownloadFileBean>) obj;
		InputStream in = null;
		try {
			for (DownloadFileBean bean : map.values()) {
				if (bean.getData() != null) {
					in = bean.getData().getInputStream();
					break;
				}
			}
		} catch (IOException e) {
			throw new SystemException("上传的文件读取错误 !", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		if (in == null) {
			throw new SystemException("没有找到上传的文件 !", SystemErrorCode.PRARAMTER_LOST_ERROR);
		}
		DataBaseService.input(in);
		ModelAndView mav = null;
		mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", 200);
		mav.addObject("message", "导入成功！");
		mav.addObject("callbackType", true);
		return mav;
	}

	/**
	 * 提交操作
	 */
	@RequestMapping("/output.html")
	public String output(HttpServletRequest request) {
		File file = DataBaseService.output();
		request.setAttribute(Download.DOWNLOAD_FILE, file);
		request.setAttribute(Download.DOWNLOAD_FILE_NAME, "数据库配置.xml");
		return "forward:/download.html";
	}
}
